<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 基本信息 -->
      <el-card class="mb-20">
        <template #header>
          <div class="card-header">
            <span class="font-bold">基本信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户来源" prop="sourceId">
              <el-select v-model="formData.sourceId" placeholder="请选择客户来源">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_CUSTOMER_SOURCE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="formData.industryId" placeholder="请选择所属行业">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_INDUSTRY)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户等级" prop="levelId">
              <el-select v-model="formData.levelId" placeholder="请选择客户等级">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_CUSTOMER_LEAVE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户意向" prop="intentId">
              <el-select v-model="formData.intentId" placeholder="请选择客户意向">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_INTENT)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 联系地址独占一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="客户介绍" prop="introduction">
              <el-input v-model="formData.introduction" placeholder="请输入客户介绍" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主要经营业务" prop="business">
              <el-input v-model="formData.business" placeholder="请输入主要经营业务" type="textarea" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 联系人信息 -->
      <el-card v-if="formType === 'create'" class="mb-20">
        <template #header>
          <div class="card-header">
            <span class="font-bold">联系人信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" placeholder="请选择性别">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="formData.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号码" prop="qq">
              <el-input v-model="formData.qq" placeholder="请输入QQ号码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 备注信息 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="font-bold">备注信息</span>
          </div>
        </template>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerApi, CustomerVO } from '@/api/oa/customer'
import ContactPersonForm from './components/ContactPersonForm.vue'

/** 客户表单 */
defineOptions({ name: 'CustomerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref<'create' | 'update'>('create') // 表单类型
const formRef = ref() // 表单 Ref
const formData = ref<CustomerVO>({
  id: 0,
  customerName: '',
  sourceId: undefined,
  address: '',
  industryId: undefined,
  levelId: undefined,
  statusId: undefined,
  intentId: undefined,
  introduction: '',
  business: '',
  contactName: '',
  phone: '',
  gender: undefined,
  email: '',
  wechat: '',
  qq: '',
  remarks: '',
  creatorName: '',
  updaterName: '',
})

// 表单校验规则
const formRules = reactive({
  customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  sourceId: [{ required: true, message: '客户来源不能为空', trigger: 'change' }],
  industryId: [{ required: true, message: '所属行业不能为空', trigger: 'change' }],
  levelId: [{ required: true, message: '客户等级不能为空', trigger: 'change' }],
})

/** 打开弹窗 */
const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (type === 'update' && id) {
    formLoading.value = true
    try {
      formData.value = await CustomerApi.getCustomer(id)
    } catch (error) {
      message.error('获取客户详情失败')
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()
  
  // 校验联系人表单
  if (formType.value === 'create') {
    const contactFormRef = document.querySelector('.contact-form') as any
    if (contactFormRef) {
      await contactFormRef.validate()
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await CustomerApi.createCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerApi.updateCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 通知父组件刷新
    emit('success')
  } catch (error) {
    message.error('提交失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: 0,
    customerName: '',
    sourceId: undefined,
    address: '',
    industryId: undefined,
    levelId: undefined,
    statusId: undefined,
    intentId: undefined,
    introduction: '',
    business: '',
    contactName: '',
    phone: '',
    gender: undefined,
    email: '',
    wechat: '',
    qq: '',
    remarks: '',
    creatorName: '',
    updaterName: '',
  }
  formRef.value?.resetFields()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb-20 {
  margin-bottom: 20px;
}
.font-bold {
  font-weight: bold;
}
:deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}
</style>